package com.test.spring.fusion.controller;

import java.util.List;

import org.spring.boot.fusion.jpa.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.JPAExpressions;
import com.querydsl.jpa.JPQLQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.test.spring.fusion.domain.QDept;
import com.test.spring.fusion.domain.QUser;
import com.test.spring.fusion.domain.User;

@RestController
public class UserController {

	@Autowired
	private JPAQueryFactory queryFactory;

	@GetMapping("test")
	public ResponseEntity<Object> test() {
		String username = "2";
		String phone = "2";
		QUser user = QUser.user;
		Predicate predicate = user.Id.isNotNull();
		if (username != null && username.trim().length() > 0 && phone != null && phone.trim().length() > 0) {
			predicate = ExpressionUtils.and(predicate, user.username.eq(username).or(user.phone.eq(phone)));
		}
		QDept dept = QDept.dept;
		JPQLQuery<Long> from = JPAExpressions.select(dept.userId).from(dept);
		predicate = ExpressionUtils.and(predicate, user.Id.in(from));
		List<User> fetch = queryFactory.selectFrom(user).where(predicate).fetch();
		return ResponseEntity.ok(fetch);
	}

	@GetMapping("page")
	public ResponseEntity<Object> page() {
		PageInfo pageInfo = new PageInfo(1, 5);
		QUser user = QUser.user;
		QueryResults<User> fetchResults = queryFactory.selectFrom(user).offset(pageInfo.getCurrent()).orderBy(user.Id.asc()).limit(pageInfo.getSize()).fetchResults();
		return ResponseEntity.ok(fetchResults);
	}
}
